<template>
  <div class="module_customization">
    <div class="module_style">
      <p>模块样式</p>
      <div class="show_content">
        <div v-for="item in moduleList" :key="item.key" class="module_num">
          <p>{{item.title}}</p>
          <div >
            <div  :class="curModuleClass === moduleItem.class ? ('active ' + moduleItem.class ): moduleItem.class " v-for="moduleItem in item.moduleItem" 
            :key="moduleItem.class" class="module_item" @click="setModule(moduleItem.class, item.key)">
              <p v-for="num in item.key" :key="num" class="module_item_tag"></p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="module_set">
      <p>模块设置</p>
      <div class="show_content" :class="module_style">
        <div  :class="curModuleClass" class="module_item_set">
          <div v-for="(item, index) in moduleData" :key="index" class="module_item_tag" @click="goToLink(item.link)" >
            <div class="module_item_Image" @click.stop >
              <el-upload class="upload_module" action="/api/api/general/upload"   
              :on-success="(response) => handleSuccess(response)"
              :on-error="handleError" :before-upload="(file) => beforeUpload(file,index)"
              :show-file-list="false" accept=".png,.jpg,.jpeg " :data="{type:'module_customization,' +curModuleClass+',' +(index + 1),imageheight: imgH, imagewidth: imgW}" >
                <el-button size="small" type="primary" @click.stop="chooseGallery(index)">图库选择</el-button>
                <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                <el-button size="small" type="primary" @click.stop="closeEditDialog(index)">编辑内容</el-button>
              </el-upload>
              <p  class="uploadTip">建议上传.jpg/.jpeg/.png格式，大小≤1M，每次只能上传一个</p>
              <div class="pop_container">
                <el-image v-if="item.image" :src="utils.setCdnUrl() + item.image" class="pop_image"></el-image>
              </div>
            </div>
            <div class="module_layer" v-show="item.image"></div>

            <div class="module_item_content"> 
              <p class="first_title" v-show="item.first_title">{{item.first_title}}</p>
              <p class="second_title" v-show="item.second_title">{{item.second_title}}</p>
              <a :class="{'noname': !item.button_name }">{{item.button_name}}</a>
            </div>
          </div>
        </div>
      </div>
      <p class="bottom_btn">
        <el-button :type="isSubmit ?'search':'disabled'" :loading="loading"
          @click="isSubmit &&!loading && submitForm()">确定</el-button>
        <el-button @click="resetForm">重置</el-button>
      </p>
    </div>
      <Drawer v-show="showDrawer" :type="'module_customization,'+curModuleClass+',' +(cur_index + 1)" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
      <Edit v-show="showEdit" :show="showEdit"  @closeDialog="closeEditDialog"></Edit>
  </div>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { Edit } from './components'
import { list, editPost } from '@/api/index/module_customization.js'
export default {
  name: 'module_customization',

  data () {
    return {
      moduleList:[
        {
          key: 4 ,
          title: '四个模块',
          moduleItem: [
            {class: "module4-1"},
            {class: "module4-2"},
            {class: "module4-3"},
            {class: "module4-4"},
          ]
        }
      ],
      curModuleClass: 'module4-1',
      curModuleNum:  4,
      module_style: '',
      moduleData: [],
      moduleDataOld: [],
      showDrawer: false,
      cur_index: '',
      imgW: '',
      imgH: '',
      showEdit: false,
      isSubmit: false,
      loading: false,
      imageOld: ''
    }
  },
  components: { Drawer, Edit },
  created() {
    this.getList()
    this.setAlignCenter()
  },
  watch: {
    curModuleClass:  function() {
      this.setAlignCenter()
    }
  },
  methods: {
    resetForm () { // 重置按钮
      this.moduleData = JSON.parse(JSON.stringify(this.moduleDataOld)) 
    },
    submitForm () {  
      this.loading = true  
      let list = this.moduleData
      for(let i = 0; i< list.length; i++){
        list[i].module_style = this.curModuleClass
        for(let j = 0; j < list[i].data.length; j ++){
          list[i].data[j].module_style = this.curModuleClass
          list[i].data[j].image = list[i].image
        }
      }
      let params = {
        data: JSON.stringify(list)
      } 
      editPost(params).then(res=>{
        if(res.state == 1){
          this.moduleDataOld  = JSON.parse(JSON.stringify(this.moduleDataOld))// 做重置功能
          this.$message.success('保存成功')   
        }
        this.loading = false
      })
    },
    validateForm ()  {
      let list = this.moduleData
      let isSubmit = true
      for(let i = 0; i < list.length; i++ ){
        if(!list[i].image){
          isSubmit = false
          break
        }
      }
      this.isSubmit = isSubmit
    },
    goToLink (link){
      if(link){
        window.open(link)
      }
    },
    getList(num) {
      let params = {}
      if(num) {
        params.module_num = num
      }
      list(params).then(res=>{
        let data = res.data
        let list = []
        if(data.length == 1 && !data[0].image) { //无历史数据
          data[0].httpImage = ''
          for(let i = 0; i < this.curModuleNum; i ++ ){
            let obj = JSON.parse(JSON.stringify(data[0] )) 
            list.push(obj)
          }
        } else {
          list = data
        
        }
        if(!num){
          this.curModuleNum = data.length || '4'
          this.curModuleClass = data[0].module_style || 'module4-1'
        }
        this.moduleData = JSON.parse(JSON.stringify(list))
        this.moduleDataOld = JSON.parse(JSON.stringify(list))
        this.validateForm()
      })
    },
    closeEditDialog (data) {
      this.showEdit = !this.showEdit
      if(typeof(data) === 'number'){
        this.cur_index = data
      } else if(data) {
        let list = JSON.parse(JSON.stringify(this.moduleData))
        list[this.cur_index].data = data
        for(let i = 0; i < data.length; i++ ){
          if(data[i].site == 'US') {
            list[this.cur_index].first_title = data[i].first_title
            list[this.cur_index].second_title = data[i].second_title
            list[this.cur_index].button_name = data[i].button_name
            list[this.cur_index].link = data[i].link
          }
        }
        this.moduleData = list
        this.validateForm()
      }

    },
    setAlignCenter () { //垂直居中的适配
      this.module_style = ''
      this.$nextTick(() =>{
        let show_content  = document.getElementsByClassName("module_set")[0].getElementsByClassName("show_content")[0]
        let module_item_set = show_content.getElementsByClassName("module_item_set")[0].scrollHeight
        if(module_item_set > show_content.clientHeight) {
          this.module_style = null
        } else {
          this.module_style =  'alignCenter'
        }
      })
    },
    setModule(data, num) {
      this.curModuleClass = data
      this.curModuleNum = num
      this.getList(num)
    },
    handleSuccess(response){
      let cur_item = this.moduleData[this.cur_index]
      cur_item.image = response.data.filePathName
      cur_item.httpImage = response.data.filePathNameHttp
      this.$message.success('上传图片成功')   
      this.validateForm()
    },
    handleError () {
      this.$message.error('上传图片失败')  
    },
    beforeUpload(file, index) {
      let that = this
      this.cur_index = index
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' &&  file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          // let valid = img.width == img.height ;
          let valid = true
          that.imgW = img.width
          that.imgH = img.height
          valid ? resolve() : reject();
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        that.$message.error('上传图片尺寸为1:1')
        return Promise.reject()
      })
      return isSize
    },
    chooseGallery (index) {
      this.showDrawer = true
      this.cur_index = index
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathName) { 
        let cur_item = this.moduleData[this.cur_index]
        cur_item.image = data.filePathName
        cur_item.httpImage = data.filePathNameHttp
        this.validateForm()
      }
      
    },
  }

}
</script>

<style lang="scss">
@import '@/styles/index/module_customization.scss';
</style>